# -*- coding: iso-8859-2 -*-

import email
import os
import logging
import traceback
import re
import string
import quopri

from authorshipanalyzer.message import Message
from authorshipanalyzer.textmodifier import MessagePreprocessor
from authorshipanalyzer.textutils import ASCIIChecker 

class Parser:
    '''
    Parser abstract class
    '''
    def __init__(self):
        self.messagePreprocessor = MessagePreprocessor()
        self.messages = []
        self.asciiChecker = ASCIIChecker() 
    
    def retrieveMessages(self, filename):
        """
        Method which parse given file and stored them 
        on the list of parsed messages
        @param filename
        """
        pass
    
    def _setApproximateDate(self, message, filename):
        '''
        If date couldn't e retrieved, the date is
        create based on file name
        @param message
        @param filename
        '''
        matcher = re.match("^.+info1.(\\d+)-(\\d+)$", filename, re.I)
        message.setDate((int(matcher.group(1)), int(matcher.group(2)), 0, 0, 0, 0, 0, 1, -1))
    
    def _appendToMessages(self, message):
        '''
        Method appending given message to message list
        if message is valid. It runs preprocess
        phase when messages are transformed and checked 
        if can be processed lately
        @param message
        '''
        if self._isValid(message):
            if self.messagePreprocessor.preprocess(message):
                self._stripSubjectLine(message)
                self.messages.append(message)
#                self.__testIfValid(message)
      
    def _stripSubjectLine(self, message):
        '''
        Remove re: and odp: from subject line
        '''
        line = message.getSubject()
        while (re.match("^(Re:|Odp:)", line, re.IGNORECASE) != None):
            if re.match("^Re:", line, re.IGNORECASE):
                line = line[3:].strip()
            else:
                line = line[4:].strip()
        message.setSubject(line)
      
    def getMessageList(self):
        '''
        @return: list of parsed and transformed messages
        '''
        return self.messages          
    
    def _isValid(self, message):
        '''
        Change message encoding if necessarry and then 
        check if message is valid
        @return: bool if message valid
        '''
        author = quopri.decodestring(message.getAuthor(), True).strip()
        if author == "":
            return False
        message.setAuthor(author)
        
        subject = quopri.decodestring(message.getSubject(), True).strip()
        if subject == "":
            return False
        message.setSubject(subject)
        
        address = quopri.decodestring(message.getAddress(), True).strip()
        if address == "":
            return False 
        message.setAddress(address)
        
        text = quopri.decodestring(message.getText(), True).strip()
        if len(text) == 0:
            return False 
        message.setText(text)
        
        '''
        Check encoding correctness
        '''
        if (self.asciiChecker.isAscii(message.getText()) == ASCIIChecker.NONE_ISO):
            return False
        
        return True
    
    def __testIfValid(self, message):
        '''
        Test is message was properly parsed
        @param: message
        '''
        f = open('/tmp/parsetest.txt', 'a')
        # text = re.sub('\n', ' ', message.getText()[:15])
        text = message.getText()
        f.write("\n\n" + message.getAuthor() + "|" + message.getSubject() + "|" + \
                message.getAddress() + "|" + str(message.getRequotationType()) + "\n") # + text + "\n\n")
        from authorshipanalyzer.textutils import Splitter
        s = Splitter()
        text = message.getText()
        wordList = s.parseText(text)
        for word in wordList:
            f.write(word + "\n")
        f.close()
    